package cs6238.common.message.response;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import cs6238.common.FileInfo;
import cs6238.common.Guard;
import cs6238.common.message.MessageId;
import cs6238.server.FileEntry;

/**
 * The response to an LsCommand
 *
 */
public class LsResponse extends Response{

	private List<FileInfo> _fileInfo;
	
	public void setFileInfoList(List<FileInfo> fileInfo){
		_fileInfo = fileInfo;
	}
	
	public List<FileInfo> getFileInfoList(){
		return _fileInfo;
	}
	
	public byte[] serialize(){
		int totalBytes = 0;
		List<byte[]> fileInfoInBytes = new ArrayList<byte[]>();
		for(FileInfo info : _fileInfo){
			byte[] infoBytes = info.serialize();
			totalBytes += infoBytes.length;
			fileInfoInBytes.add(infoBytes);
		}
		
		ByteBuffer bb = ByteBuffer.allocate(4 + 4 + totalBytes);
		bb.putInt(MessageId.LS_RESPONSE.ordinal());
		bb.putInt(fileInfoInBytes.size());

		for(byte[] byteArray : fileInfoInBytes){
			bb.put(byteArray);
		}
		
		return bb.array();
	}
	
	public void deserialize(byte[] buffer){
		Guard.that(buffer != null && buffer.length >= 4, "LsResponse buffer is too short to deserialize");
		
		ByteBuffer bb = ByteBuffer.wrap(buffer);
		bb.getInt();
		
		_fileInfo = new ArrayList<FileInfo>();
		int numFileInfoItems = bb.getInt();
		for(int i=0; i<numFileInfoItems; i++){
			FileInfo info = new FileInfo();
			info.deserialize(bb);
			_fileInfo.add(info);
		}
	}
	
	public void createFileInfoList(List<FileEntry> files){
		ArrayList<FileInfo> result = new ArrayList<FileInfo>();
		
		for(FileEntry meta : files){
			result.add( meta.createFileInfo() );
		}
		
		_fileInfo = result;
	}
}
